<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>上传单个文件</title>
    <style>
      * {
        font-size: 28px;
      }
    </style>
  </head>

  <body>
    <input id="uploadFile" type="file" accept="image/*" />

    <button type="button" id="uploadBtn" onClick="startUpload()">开始上传</button>
    <div class="progress">上传进度：<span id="progressValue">0</span></div>

    <div id="uploadResult" class="result"></div>

    <script>
      const uploadFileEle = document.getElementById("uploadFile");
      const progressValueEle = document.getElementById("progressValue");
      const uploadResultEle = document.getElementById("uploadResult");

      try {
        function startUpload() {
          if (!uploadFileEle.files.length) return;
          // 获取文件
          const file = uploadFileEle.files[0];
          // 创建上传数据
          const formData = new FormData();
          formData.append("file", file);
          // 上传文件
          upload(formData);
        }

        function upload(data) {
          const xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
              const result = JSON.parse(xhr.responseText);
              console.log("result:", result);
              uploadResultEle.innerText = xhr.responseText;
            }
          };

          xhr.upload.onprogress = function (event) {
            if (event.lengthComputable) {
              progressValueEle.innerText = Math.ceil((event.loaded * 100) / event.total) + "%";
            }
          };

          xhr.open("POST", "http://127.0.0.1:3000/upload", true);
          xhr.send(data);
        }
      } catch (e) {
        console.log("error:", e);
      }
    </script>
  </body>
</html>
